<template>
  <div>
    <Title :title="title"></Title>
    <div ref="bottom3" style="height: 150px;"></div>
  </div>
</template>

<script setup>
import Title from './Title.vue';
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { Line } from '@antv/g2plot';
import { get } from '@/utils/request';

const bottom3 = ref(null);
const title = ref('实时风速-时间折线图');
const windData = ref([]);
const linePlot = ref(null);
const refreshTimer = ref(null);
let isFirstLoad = true;
let lastUpdateTime = new Date(); // 记录上次更新时间

// 获取当前时间字符串（格式：HH:mm）
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 生成时间点数组（基于基准时间生成最近6个时间点）
const generateTimePoints = (baseTime = new Date()) => {
  const timePoints = [];
  for (let i = 5; i >= 0; i--) {
    const time = new Date(baseTime - i * 60000); // 前i分钟
    timePoints.push(`${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`);
  }
  return timePoints;
};

// 生成模拟数据（以时间为x轴，风速为y轴）
const generateMockData = (baseTime = new Date()) => {
  const timePoints = generateTimePoints(baseTime);
  return timePoints.map(time => {
    const baseSpeed = 3 + Math.random() * 2;
    const randomFluctuation = (Math.random() - 0.5) * 0.2;
    const speed = Math.max(0, baseSpeed + randomFluctuation).toFixed(1);
    
    return { time, speed: parseFloat(speed) };
  });
};

// 获取风速数据（绑定当前时间）
const fetchWindData = async () => {
  try {
    const now = new Date();
    const res = await get('/api/environment/wind-speed-by-time');
    console.log('时间风速数据获取成功', res);
    
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      // 使用接口时间或当前时间
      const timePoints = generateTimePoints(now);
      return res.data.map((item, index) => ({
        time: timePoints[index],
        speed: parseFloat(item.speed.toFixed(1)),
      }));
    } else {
      console.log('服务器返回空数据，使用模拟数据');
      return generateMockData(now);
    }
  } catch (error) {
    console.error('获取时间风速数据失败', error);
    return generateMockData(new Date());
  }
};

// 初始化图表
const initChart = () => {
  if (!bottom3.value || !windData.value.length) return;
  
  if (linePlot.value) {
    linePlot.value.destroy();
  }
  
  linePlot.value = new Line(bottom3.value, {
    data: windData.value,
    xField: 'time',
    yField: 'speed',
    color: '#66ffff',
    label: {
      visible: true,
      position: 'top',
      style: {
        fill: 'white',
      },
    },
    xAxis: {
      label: {
        style: {
          fill: 'white',
          fontSize: 8,
          rotate: 45, // 倾斜45度避免重叠
          interval: 0, // 显示所有标签
        },
      },
      type: 'category', // 时间作为分类轴
    },
    yAxis: {
      label: {
        style: {
          fill: 'white',
        },
      },
      title: {
        text: '风速(m/s)',
        style: {
          fill: 'white',
        },
      },
    },
    smooth: true, // 添加弧度
    point: {
      size: 4, // 转折点标注
      shape: 'circle',
      style: {
        fill: 'white',
        stroke: '#66ffff',
        lineWidth: 2,
      },
    },
    interactions: [{ type: 'marker-active' }], // 支持点交互
    state: {
      active: {
        point: {
          style: {
            fill: 'red',
            stroke: 'red',
          },
        },
      },
    },
  });
  
  linePlot.value.render();
};

// 平滑更新数据（保留时间标签）
const smoothUpdateData = (newData) => {
  const originalData = [...windData.value];
  
  // 保持时间标签不变，只更新风速值
  if (originalData.length === newData.length) {
    for (let i = 0; i < newData.length; i++) {
      originalData[i].speed = parseFloat((
        originalData[i].speed * 0.8 + 
        newData[i].speed * 0.2
      ).toFixed(1));
    }
    windData.value = originalData;
  } else {
    windData.value = newData;
  }
};

// 定时刷新数据（1分钟刷新一次）
const startRefresh = async () => {
  try {
    const data = await fetchWindData();
    lastUpdateTime = new Date(); // 更新时间戳
    windData.value = data;
    initChart();
    isFirstLoad = false;
    
    // 60秒 = 60000毫秒
    refreshTimer.value = setInterval(async () => {
      const now = new Date();
      const newData = await fetchWindData();
      lastUpdateTime = now; // 更新时间戳
      
      if (!isFirstLoad) {
        smoothUpdateData(newData);
      } else {
        windData.value = newData;
      }
      
      if (linePlot.value) {
        linePlot.value.changeData(windData.value);
      }
    }, 60000);
  } catch (error) {
    console.error('初始化数据失败', error);
  }
};

// 停止刷新
const stopRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
};

onMounted(() => {
  startRefresh();
});

onUnmounted(() => {
  stopRefresh();
  if (linePlot.value) {
    linePlot.value.destroy();
  }
});

watch(windData, (newData) => {
  if (linePlot.value && newData.length) {
    linePlot.value.changeData(newData);
  }
});
</script>

<style lang="less" scoped>
/* 优化时间标签间距 */
:deep(.g2-legend-item-text) {
  fill: white;
  font-size: 10px;
}
:deep(.g2-axis-label) {
  padding-bottom: 8px; /* 增加标签与轴的间距 */
}
</style>